<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- layout布局 -->
      <el-row :gutter="9">
        <el-col :span="7">
          <el-input
            clearable
            placeholder="请输入内容"
            v-model="userParse.query"
            class="input-with-select"
            @clear="clearInput"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList()"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >增加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 表单区域 -->
      <el-table :data="userList">
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="状态">
          <!-- 插槽的用处 -->
          <template slot-scope="scope">
            <!-- {{scope.row}} 对象的值 -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editClick(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setUserByRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userParse.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="userParse.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 新增对话框区域 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="40%" @close="addDialogClose">
      <el-form
        :model="addUserForm"
        :rules="addUserRules"
        ref="addUserRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model.number="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserOk"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 修改对话框区域 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="40%" @close="editDialogClose">
      <el-form
        :model="editUserForm"
        :rules="addUserRules"
        ref="editUserRef"
        label-width="70px"
      >
        <el-form-item label="用户名" >
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model.number="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserOk"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
        <!-- 新增对话框区域 -->
    <el-dialog
      title="分配角色"
      :visible.sync="addRoleDialogVisible"
      width="40%"
      @close="addRoleDialogClose"
    >
    <div>
      <p>用户名：{{userInfoRole.username}}</p>
      <p>用户名：{{userInfoRole.role_name}}</p>
    </div>
    <div style="display: flex;">
      <p>分配新角色：</p>
      <el-select v-model="selectedRole" placeholder="请选择">
      <el-option
        v-for="item in roleList"
        :key="item.id"
        :label="item.roleName"
        :value="item.id">
      </el-option>
    </el-select>
    </div>
    <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleOk">确 定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
import { queryUserList, addUser } from '@/api/index.js'

export default {
  data() {
    return {
      dialogVisible: false,
      userList: [],
      userParse: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      total: 0,
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '用户名的长度在3-15字符之间',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '密码的长度在3-15字符之间',
            trigger: 'blur',
          },
        ],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' },
         {
            type:'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change'],
          },
        ],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' },{ type: 'number', message: '电话号码必须为数字值'}],
      },
      // 修改的模态框
      editDialogVisible : false,
      editUserForm: {
        id:"",
        username: '',
        // password: '',
        email: '',
        mobile: '',
      },
      addRoleDialogVisible:false,
      userInfoRole:{},
      roleList:[],
      selectedRole:""
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const res = await queryUserList(this.userParse)
      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg)
      }
      this.total = res.data.total
      this.userList = res.data.users
      console.log(res)
    },
    // 每页显示多少条数据的改变的回调函数
    handleSizeChange(newSize) {
      this.userParse.pagesize = newSize
      this.getUserList()
    },
    // 分页改变的回调函数
    handleCurrentChange(newPageNum) {
      this.userParse.pagenum = newPageNum
      this.getUserList()
    },
    // 修改用户状态
    // 监听 switch 开关状态的改变
    async userStateChanged(userinfo) {
      console.log(userinfo)
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户状态失败！')
      }
      this.$message.success('更新用户状态成功！')
    },
    // 搜索输入框的清除事件
    clearInput() {
      this.getUserList()
    },
    // 监听对话框close事件
    addDialogClose(){
      // resetFields 清空表单
      this.$refs.addUserRef.resetFields();
    },
    // 监听对话框close事件
    editDialogClose(){
      // resetFields 清空表单
      this.$refs.editUserRef.resetFields();
    },
    // 表单确认的事件
    addUserOk(){
      this.$refs.addUserRef.validate(async value=>{
        // 表单验证不通过
        if(!value) return
        const res =  await addUser(this.addUserForm)
        console.log(res);
        if(res.meta.status != 201){
          return  this.$message.error('创建失败')
        }
         this.$message.success('创建成功')
         // 刷新数据
         this.getUserList();
        // 关闭对话框
        this.dialogVisible = false;
      })
    }, 
    // 修改单击事件
    async editClick(id) {
      console.log(id);
      this.editDialogVisible = true
      let {data : res} =   await this.$http.get('users/'+id)
      let userInfo = res.data;
      this.editUserForm.username = userInfo.username;
      this.editUserForm.id = id;
      this.editUserForm.email = userInfo.email;
      this.editUserForm.mobile = Number(userInfo.mobile);
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败！')
      }
    },
    // 修改表单的确认事件
   async editUserOk(){
        this.$refs.editUserRef.validate(async value=>{
          if(!value) return
        })
        let {data : res} =   await this.$http.put('users/'+this.editUserForm.id, this.editUserForm);
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败！')
        }
      this.$message.success('更新用户信息成功！')
      this.editDialogVisible = false;
      this.getUserList();
    },
    // 删除用户
    async deleteUser(id){
       let resultConfirm =  await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(resultConfirm);
      if(resultConfirm != "confirm"){
          return this.$message.warning('取消删除')
      }
      let {data : res} =   await this.$http.delete('users/'+id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败！')
      }
      this.$message.success('删除用户信息成功！')
      this.getUserList();
    },
    // 关闭角色框
    addRoleDialogClose(){
      this.selectedRole = null
    },
    // 添加角色
    async addRoleOk(){
      if(!this.selectedRole){
         return this.$message.error('请选择新角色')
      }
      let {data : res} =   await this.$http.put(`users/${this.userInfoRole.id}/role`,{rid:this.selectedRole});
      if (res.meta.status !== 200) {
        return this.$message.error('更新角色失败！')
      }
      this.$message.success('更新角色信息成功！')
      this.getUserList();
      this.addRoleDialogVisible  = false
    },
    // 点击分配角色的事件
    async setUserByRole(info){
      console.log(info);
      this.userInfoRole = info;
      let {data : res} =   await this.$http.get('roles')
       if (res.meta.status !== 200) {
        return this.$message.error('查询角色信息失败！')
      }
      this.roleList = res.data
      this.addRoleDialogVisible = true;
    }

  },
}
</script>

<style lang="less" scoped>
</style>